<template>
  <div class="manage_sels" ref="kfs">
    <!-- 模拟input框内容 start -->
    <div class="item my_ipt" ref="myipt" @click.stop="showDialog">
      <el-tag
        closable
        size="small"
        type="info"
        @close="clearChoose(index, item)"
        v-for="(item, index) in submitResult"
        :key="index"
        style="margin-right: 6px; margin-bottom: 6px"
      >
        {{ item.name }}
      </el-tag>
    </div>
    <!-- 弹框 -->
    <el-dialog
      ref="wDialog"
      :visible="visible"
      :append-to-body="true"
      :close-on-click-modal="false"
      width="600px"
      @close="close"
      title="设置管理部门"
    >
      <div class="dep_container box manage_abs">
        <div class="dep_content">
          <div class="dep_left">
            <div class="left_tit">部门列表</div>
            <el-input
              prefix-icon="el-icon-search"
              placeholder="请输入搜索内容"
              class="search_ipt"
              v-model="filtersText"
            ></el-input>
            <div class="dep_tree">
              <el-tree
                :data="dataTree"
                show-checkbox
                node-key="id"
                ref="dep_tree"
                highlight-current
                :props="defaultProps"
                :filter-node-method="filterNode"
                :check-strictly="true"
                :default-expand-all="true"
                @check="handleCheckChange"
              >
              </el-tree>
            </div>
          </div>
          <div class="dep_right">
            <div class="right_tit">
              <span>已选择部门（{{ chooseResult.length }} ）</span>
              <span @click="clearSelects">清空全部</span>
            </div>
            <div class="choose_box">
              <div
                class="item"
                style="padding: 0; margin: 0; margin-bottom: 8px"
                v-for="(item, index) in chooseResult"
                :key="index"
              >
                <el-tag
                  closable
                  type="info"
                  @close="clearChoose(index, item)"
                  color="#F6F7FC"
                >
                  {{ item.name }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="submitDeps">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
/** 部门选择器---多选*/
import { depListAPI } from "@/api/common";
export default {
  data() {
    return {
      defaultProps: {
        children: "children",
        label: "label"
      },
      chooseResult: [], //勾选的节点
      chooseKeys: [], //勾选的节点的key
      submitResult: [], //input框回显内容
      filtersText: "", //搜索字段
      visible: false,
      dataTree: [], //树结构数据
      tempDataTree: [], //树结构数据 替换
      excludeKeys: []
    };
  },
  props: ["manageDeptId", "manageDeptName"],
  watch: {
    filtersText(val) {
      this.$refs.dep_tree.filter(val);
    },
    manageDeptId: {
      /**
       * input框-回显已选项
       */
      handler(val) {
        if (val) {
          let selArr = val.split(",");
          let selName = this.manageDeptName.split(",");
          this.chooseKeys = selArr;
          selArr.forEach((item, index) => {
            this.$set(this.submitResult, index, { name: selName[index] });
          });
        }
      },
      immediate: true,
      deep: true
    }
  },
  mounted() {
    /**
     * 获取树形列表
     */
    this.getDepTreeList();
  },
  methods: {
    /**
     * 树结构-回显已选项
     */
    showDialog() {
      this.visible = true;
      if (this.chooseKeys) {
        this.$nextTick(() => {
          if (this.$refs.dep_tree) {
            this.$refs.dep_tree.setCheckedKeys(this.chooseKeys);
            this.chooseResult = this.$refs.dep_tree.getCheckedNodes();
          }
        });
      } else if (this.manageDeptId) {
        let selArr = this.manageDeptId.split(",");
        this.$nextTick(() => {
          if (this.$refs.dep_tree) {
            this.$refs.dep_tree.setCheckedKeys(selArr);
          }
        });
      }
    },
    /**
     * 获取树形列表
     */
    getDepTreeList() {
      depListAPI({ type: "tree" }).then(response => {
        this.dataTree = response.data || [];
        this.tempDataTree = this.dataTree;
      });
    },
    close() {
      this.visible = false;
    },
    /**
     * 勾选操作
     */
    handleCheckChange(data, indeterminate) {
      const newData = { ...data, children: null };
      // 选择的节点中不包含当前点击的，添加
      if (indeterminate.checkedKeys.indexOf(data.id) > -1) {
        this.chooseResult.push(newData);
        this.chooseKeys.push(newData.id);

        // 删除树形结构中的childrent
        this.dataTree.forEach(node => {
          this.traverseTree(node, newData.id);
        });
        // console.log(this.$refs.dep_tree.getCheckedKeys());
      } else {
        // 包含则删除
        this.chooseResult.forEach((item, index) => {
          if (item.id === newData.id) {
            this.chooseResult.splice(index, 1);
            this.chooseKeys.splice(index, 1);

            // 将删除的childrent重新添加到树结构中
            this.tempDataTree.forEach(node => {
              this.traverseTree(node, newData.id);
            });
          }
        });
      }
    },

    // 添加删除children
    traverseTree(node, id, data) {
      if (node.id === id && !data) {
        // 查看当前选中的数据中是否有选中的子集，如果有就删除
        if (node.children && node.children.length > 0) {
          const keyList = this.chooseKeys;
          keyList.splice(this.chooseKeys.indexOf(node.id), 1)
          console.log(keyList);
          node.children.forEach(item => {
            let result = this.findChildren(
              node.children,
              keyList
            );
            console.log(result, this.chooseResult);
            // if (result) {
            //   this.chooseResult.splice(this.chooseResult.indexOf(result), 1);
            //   this.chooseKeys.splice(this.chooseKeys.indexOf(result.id), 1);
            // }
          });
        }
        // node.children = null;
      } else if (data) {
        node.children = data.children;
      }
      
      if (node.children && node.children.length > 0) {
        node.children.forEach(child => {
          this.traverseTree(child, id, data);
        });
      }
    },

    /**
     * 查找当前选中的数据中是否有选中的子集
     * @param {*} data 查找的子集
     * @param {*} idList 选中的id列表
     */
    findChildren(data, idList) {
      let result = null;
      data.forEach((item, index) => {
        idList.forEach(id => {
          if (item.id == id) {
            result = item;
          } else if (item.children && item.children.length > 0) {
            result = this.findChildren(item.children, idList);
          }
        });
      });
      return result;
    },

    /**
     * 清空-单个
     */
    clearChoose(idx) {
      this.chooseResult.splice(idx, 1);
      this.chooseKeys.splice(idx, 1);
      this.submitResult.splice(idx, 1);
      this.$nextTick(() => {
        if (this.$refs.dep_tree) {
          this.$refs.dep_tree.setCheckedKeys(this.chooseKeys);
        }
      });
    },
    /**
     * 清空-所有
     */
    clearSelects() {
      this.chooseResult = [];
      this.chooseKeys = [];
      this.$refs.dep_tree.setCheckedNodes([]);
    },
    /**
     * 筛选
     */
    filterNode(value, data, node) {
      if (!value) return true;
      return this.chooseNode(value, data, node);
    },
    /**
     * 筛选
     */
    chooseNode(value, data, node) {
      if (data.label.indexOf(value) !== -1) {
        return true;
      }
      const level = node.level;
      if (level === 1) {
        return false;
      }
      let parentData = node.parent;
      let index = 0;
      while (index < level - 1) {
        if (parentData.data.label.indexOf(value) !== -1) {
          return true;
        }
        parentData = parentData.parent;
        index++;
      }
      return false;
    },
    /**
     * 提交操作
     */
    submitDeps() {
      this.submitResult = this.chooseResult;
      this.visible = false;
      this.$emit("submitDeps", this.chooseKeys.join(","));
    }
  }
};
</script>
<style scoped lang="scss">
.manage_sels {
  width: 100%;
  border-radius: 3px;
  border: 1px solid #e6e6e6;
  min-height: 34px;
  cursor: pointer;
  position: relative;
  padding: 0 6px;
  .manage_abs {
    position: absolute;
    z-index: 100000;
    // top: 45px;
    top: 50px;
    right: 0;
  }
  .sanjiao {
    position: absolute;
    content: "";
    top: 45px;
    right: 50px;
    width: 0;
    height: 0;
    border-bottom: 6px solid #ebeef5;
    border-right: 6px solid transparent;
    border-left: 6px solid transparent;
    display: inline-block;
  }
  .my_ipt {
    width: 100%;
    display: flex;
    align-items: center;
    min-height: 34px;
    flex-wrap: wrap;
    padding-top: 6px;
  }
  .my_ipt /deep/ .el-tag__close {
    background: #c0c4cc;
  }
}
.dep_container {
  background: white;
  width: 100%;
  height: 469px;

  .dep_content {
    display: flex;
    height: 496px;

    border: 1px solid #eeeeee;
  }
  .dep_left {
    width: 300px;
    border-right: 1px solid #eeeeee;
    display: flex;
    height: 100%;
    flex-direction: column;
    .left_tit {
      height: 40px;
      background: #f6f7fc;
      font-size: 13px;
      line-height: 36px;
      color: #333333;
      padding-left: 15px;
    }
    .search_ipt {
      width: 90%;
      height: 32px;
      margin-left: 16px;
      margin-bottom: 15px;
      margin-top: 8px;
      /deep/ .el-input__inner {
        background: #f6f7fc !important;
        border: none !important;
      }
    }
    .dep_tree {
      height: calc(100% - 40px - 32px - 15px - 8px);
      overflow: scroll;
    }
  }
  .dep_right {
    width: 300px;
    .right_tit {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 40px;
      padding-left: 15px;
      padding-right: 15px;
      border-bottom: 1px solid #f4f4f4;
      span {
        font-size: 13px;
        color: #333333;
      }
      span:last-child {
        color: #5e9df9;
        cursor: pointer;
      }
    }
    .choose_box {
      margin-top: 8px;

      height: calc(100% - 50px);
      width: 100%;
      overflow: scroll;
      padding-left: 16px;
      padding-right: 16px;
      .item {
        margin-bottom: 8px;
      }
      /deep/ .el-tag.el-tag--info {
        border-color: transparent !important;
      }
    }
  }
  .dep_footer {
    height: 48px;
    background: #f7f8fa;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding-right: 17px;
  }
}
</style>
